﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;
using YSC_Data.BLL.DBContext;

namespace YSC_WXAPP_WebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddMvcCore(option =>
            {
                option.Filters.Add(new TestAuthorizationFilter());
            }).AddAuthorization()
              .AddJsonFormatters();

            services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    //http://localhost:5000
                    //http://yscoauth.cnfm.com.cn:8099
                    options.Authority = "http://yscoauth.cnfm.com.cn:8099";
                    // options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;

                    options.Audience = "api1";
                });

            #region Swagger
            //https://github.com/domaindrivendev/Swashbuckle.AspNetCore
            services.AddSwaggerGen(c =>
            {

                c.SwaggerDoc("v1", new Info { Title = "YSC API", Version = "v1" });
                c.DocInclusionPredicate((docName, description) => true);
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "Authorization format : Bearer {token}",
                    Name = "Authorization",
                    In = "header",
                    Type = "apiKey"
                });//api界面新增authorize按钮

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath, true);
            });
            #endregion


            #region Scrutor
            //scrutor 注册

            // 自动地发现并注册指定的服务
            services.Scan(
                x =>
                {
                    var entryAssembly = Assembly.GetEntryAssembly();
                    var referencedAssemblies = entryAssembly.GetReferencedAssemblies().Select(Assembly.Load);
                    var assemblies = new List<Assembly> { entryAssembly }.Concat(referencedAssemblies);

                    x.FromAssemblies(assemblies)
                             .AddClasses(classes => classes.Where(t => t.Name.EndsWith("AppServices", StringComparison.OrdinalIgnoreCase)))
                            .AsImplementedInterfaces()
                            .WithScopedLifetime()


                                  .AddClasses(classes => classes.Where(t => t.Name.EndsWith("DBContext", StringComparison.OrdinalIgnoreCase)))
                            .AsImplementedInterfaces()
                            .WithScopedLifetime()

                             .AddClasses(classes => classes.Where(t => t.Name.EndsWith("Repository", StringComparison.OrdinalIgnoreCase)))
                            .AsImplementedInterfaces()
                            .WithScopedLifetime();
                });



            //EF上下文注册
            services.Scan(scan => scan
                 .AddTypes(typeof(EntityFrameworkDbContext))
                         .AsSelf()
                       .WithSingletonLifetime()
                     );

            #endregion
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            app.UseStaticFiles();
            //  _ = app.UseSwaggerUI(options => options.SwaggerEndpoint("/swagger/doc/swagger.json", null));
            _ = app.UseSwagger();
            _ = app.UseAuthentication();
            _ = app.UseHttpsRedirection();
            _ = app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.OAuthClientId("api1_client");
                c.OAuthAppName("api1 描述"); // 描述
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            _ = app.UseMvc();
        }
    }
}
